package com.xyoto.takeawayBusiness.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.xyoto.takeawayBusiness.constant.DataBasesOperationResult;
import com.xyoto.takeawayBusiness.constant.FileModelConstant;
import com.xyoto.takeawayBusiness.constant.OrderType;
import com.xyoto.takeawayBusiness.constant.OrdersStatus;
import com.xyoto.takeawayBusiness.dto.*;
import com.xyoto.takeawayBusiness.entity.Shop;
import com.xyoto.takeawayBusiness.entity.TakeawayManager;
import com.xyoto.takeawayBusiness.enums.*;
import com.xyoto.takeawayBusiness.exception.ExceptionUtils;
import com.xyoto.takeawayBusiness.mapper.*;
import com.xyoto.takeawayBusiness.service.ShopService;
import com.xyoto.takeawayBusiness.utils.*;
import com.xyoto.takeawayBusiness.vo.BillSumVO;
import com.xyoto.takeawayBusiness.vo.BillVO;
import com.xyoto.takeawayBusiness.vo.GetTakeawayVO;
import com.xyoto.takeawayBusiness.vo.ShopDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author: TingFeng
 * @CreateTime: 2022/5/4  15:23
 */
@Service
@Slf4j
public class ShopServiceImpl implements ShopService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ShoppingTypeServiceImpl shoppingTypeService;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private TakeawayManagerMapper takeawayMapper;
    @Resource
    private BillMapper billMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private OrderMapper orderMapper;



    /**
     * 获取店铺资料
     * @param shopId
     * @return
     */
    @Override
    public Result getShopData(Integer shopId) {
        Integer thisUserShopId = shoppingTypeService.findThisUserShopId();
        if(!thisUserShopId.equals(shopId)){
            log.info("该用户无查询其他店铺权限");
            ExceptionUtils.error(CommonEnum.ILLEGAL_REQUEST);
        }
        log.info("开始获取商铺信息");
        ShopDataVo shopData = shopMapper.getShopData(shopId);
        if (shopData==null) {
            log.info("商铺信息未找到");
            ExceptionUtils.error(ShopEnum.SHOP_DATA_NO_FIND);
        }

        log.info("查询成功");

        return Result.success(shopData);
    }

    /**
     * 获取外卖管理
     * @param shopId
     * @return
     */
    @Override
    public Result getTakeaway(Integer shopId) {
        Integer thisUserShopId = shoppingTypeService.findThisUserShopId();
        if(!thisUserShopId.equals(shopId)){
            log.info("该用户无查询其他店铺权限");
            ExceptionUtils.error(CommonEnum.ILLEGAL_REQUEST);
        }
        GetTakeawayVO takeaway = takeawayMapper.getTakeaway(shopId);
        log.info("开始查询外卖管理信息");
        if (takeaway==null) {
            log.info("外卖管理信息未找到");
            ExceptionUtils.error(ShopEnum.TAKEAWAY_MANAGER_NO_FIND);
        }
        log.info("查询成功");
        return Result.success(takeaway);
    }

    /**
     * 获取菜单
     * @param pageUtils
     * @param billDTO
     * @return
     */
    @Transactional
    @Override
    public Result getBill(PageUtils pageUtils, BillDTO billDTO) {
        Integer thisUserShopId = shoppingTypeService.findThisUserShopId();
        log.info(thisUserShopId+"  ---"+billDTO.getShopId());
        if(!thisUserShopId.equals(billDTO.getShopId())){
            log.info("该用户无查询其他店铺权限");
            ExceptionUtils.error(CommonEnum.ILLEGAL_REQUEST);
        }
        log.info("进行时间转换");
        String time=billDTO.getTime();
        DateTimeFormatter date = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        TemporalAccessor parse = date.parse(time);
        LocalDate startDay = LocalDate.from(parse);
        LocalDate endDay = startDay.plusDays(1);
        Date start = Date.valueOf(startDay);
        Date end = Date.valueOf(endDay);
        log.info("开始查询");
        short completed = OrdersStatus.COMPLETED;
        PageHelper.startPage(pageUtils.getPageNum(),pageUtils.getPageSize());
        List<BillVO> billVOList = billMapper.getBills(billDTO.getShopId(),end,start,completed);
         //分页
        PageUtils<BillVO> list = PageUtils.restPage(billVOList);
        BillSumVO billSumVO = billMapper.getSumCount(billDTO.getShopId(),end,start,completed);

        log.info("成功");
        HashMap<String, Object> map = new LinkedHashMap<>();
        map.put("total",billSumVO.getBillCount());
        map.put("sumPay",billSumVO.getPaySum());
        map.put("data",list);

        return Result.success(map);
    }

    /**
     * 修改外卖管理
     * @param takeawayDTO
     * @return
     */
    @Override
    public Result updateTakeaway(UpdateTakeawayDTO takeawayDTO) {
        Integer thisUserShopId = shoppingTypeService.findThisUserShopId();
        log.info(thisUserShopId+"  ---"+takeawayDTO.getShopId());
        if(!thisUserShopId.equals(takeawayDTO.getShopId())){
            log.info("该用户无修改其他店铺权限");
            ExceptionUtils.error(CommonEnum.ILLEGAL_REQUEST);
        }
        log.info("外卖管理开始修改");
        int i =takeawayMapper.updateTakeaway(takeawayDTO);
        if(i == DataBasesOperationResult.ERROR){
            log.info("外卖管理修改失败");
            ExceptionUtils.error(ShopEnum.TAKEAWAY_MANAGER_UPDATE_ERROR);
        }
        log.info("外卖管理修改成功");
        return Result.success();
    }

    /**
     * 修改订单状态
     * @param updateDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateOrderStatus(UpdateOrderStatusDto updateDto) {

        // 校验订单状态范围
        JudgeParamUtils.judgeOrderStatus(updateDto.getStatus());

        Integer count = orderMapper.isExistOrder(updateDto.getOrderId());
        if (count == null || !count.equals(DataBasesOperationResult.SUCCESS)){
            ExceptionUtils.error(OrderEnum.ORDER_NOT_EXIST);
        }

        // 处理订单类型
        Short type = parseOrderType(updateDto.getStatus());
        Integer status = orderMapper.updateOrderStatus(updateDto.getStatus(), updateDto.getOrderId(), type);
        if (status == null || status.equals(DataBasesOperationResult.ERROR)){
            ExceptionUtils.error(OrderEnum.ORDER_STATUS_UPDATE_FAIL);
        }
        return Result.success();
    }

    private Short parseOrderType(Short status){
        Short type = null;
        switch (status){
            case 2:
                // 已送达
                type = OrderType.COMPLEATED;
                break;
            case 3:
                // 接单打印
                type = OrderType.PROCESSING;
                break;
            case 8:
                // 拒绝新订单
                type = OrderType.NEW_ORDER;
                break;
                default:
        }
        return type;
    }

    /**
     * 新增外卖管理
     * @param addTakeawayDTO
     * @return
     */
    @Override
    public Result addTakeaway(AddTakeawayDTO addTakeawayDTO) {
        Integer thisUserShopId = shoppingTypeService.findThisUserShopId();
        if(!thisUserShopId.equals(addTakeawayDTO.getShopId())){
            log.info("该用户无新增其他店铺权限");
            ExceptionUtils.error(CommonEnum.ILLEGAL_REQUEST);
        }
        log.info("判断是否已有外卖管理");
        Integer i= takeawayMapper.findTakeawayManagerCount(thisUserShopId);
        if(i!=DataBasesOperationResult.ERROR){
            log.info("已有外卖管理");
            ExceptionUtils.error(ShopEnum.TAKEAWAY_MANAGER_HAVE_FIND);
        }
        log.info("开始新增外卖管理");
        TakeawayManager takeawayManager = new TakeawayManager();
        BeanUtils.copyProperties(addTakeawayDTO,takeawayManager);
        Integer count = takeawayMapper.addTakeaway(takeawayManager);
        if(count==DataBasesOperationResult.ERROR){
            log.info("添加失败");
            ExceptionUtils.error(ShopEnum.TAKEAWAY_ADD_ERROR);
        }
        log.info("添加成功");

        return Result.success();
    }

    /**
     *
     * 修改/完善店铺信息
     * @param shopInfoDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateShopInfo(UpdateShopInfoDto shopInfoDto) {
        JudgeParamUtils.judgeIntegerParam(shopInfoDto.getId(), ShopEnum.USER_SHOP_NOT_EXIST);

        // 查询店铺信息
        Shop shop = shopMapper.getShopInfo(shopInfoDto.getId());
        if (Objects.isNull(shop)){
            ExceptionUtils.error(ShopEnum.USER_SHOP_NOT_EXIST);
        }

        // 修改信息
        if (!StrUtil.isEmpty(shopInfoDto.getShopName())){
            shop.setShopName(shopInfoDto.getShopName());
        }
        if (!StrUtil.isEmpty(shopInfoDto.getAddress())){
            shop.setAddress(shopInfoDto.getAddress());
        }
        if (!StrUtil.isEmpty(shopInfoDto.getArea())){
            shop.setArea(shopInfoDto.getArea());
        }
        if (!StrUtil.isEmpty(shopInfoDto.getName())){
            shop.setName(shopInfoDto.getName());
        }
        if (!StrUtil.isEmpty(shopInfoDto.getPhone())){
            shop.setPhone(shopInfoDto.getPhone());
        }
        if (shopInfoDto.getCategoryId() != null){
            JudgeParamUtils.judgeIntegerParam(shopInfoDto.getCategoryId(), CategoryEnum.CATEGORY_NOT_EXIST);
            // 查询类别
            Integer count = categoryMapper.isExistCategory(shopInfoDto.getCategoryId());
            JudgeParamUtils.judgeIntegerParam(count, CategoryEnum.CATEGORY_NOT_EXIST);
            shop.setCategoryId(shopInfoDto.getCategoryId());
        }
        if (shopInfoDto.getPath() != null){
            try {
                String path = minioUtils.uploadFile(shopInfoDto.getPath(), FileModelConstant.SHOP_LOGO);
                if (StrUtil.isEmpty(path)){
                    ExceptionUtils.error(ShopEnum.SHOP_LOGO_SAVE_FAIL);
                }
                shop.setPath(path);
            } catch (Exception e) {
                log.info("——店铺logo存储失败——");
                ExceptionUtils.error(ShopEnum.SHOP_LOGO_SAVE_FAIL);
            }
        }
        if (shopInfoDto.getBusinessTimeStart() != null){
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            try {
                java.util.Date startTime = sf.parse(shopInfoDto.getBusinessTimeStart());
                shop.setBusinessTimeStart(startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (shopInfoDto.getBusinessTimeEnd() != null){
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            try {
                java.util.Date endTime = sf.parse(shopInfoDto.getBusinessTimeEnd());
                shop.setBusinessTimeEnd(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Integer flag = shopMapper.updateShopInfo(shop);
        if (flag == null || flag.equals(DataBasesOperationResult.ERROR)){
            ExceptionUtils.error(ShopEnum.SHOP_UPDATE_FAIL);
        }
        return Result.success();
    }
}
